import {toast, cloneDataFunc} from "../../utils/tool";
import EventBus from "../../utils/eventBus";
import {NAME_ENUM} from "../../constant/index";

const app = getApp()
const heightArr = []
// const NAME_ENUM = 'order_cache'
Page({
    data: {
        category: [],
        activeCateIndex: 0,
        leftID: 'cate_0',
        rightID: 'shop_0',
        shopList: [],
        roomList: [],
        activeRoom: {
            id: '',
            name: ''
        },
        show: false,
        defaultIndex: 0,
        store: {},
        banner: [],
        cartData: {},
        currentGoodList: [],
        totalNum: 0,
        totalPrice: 0,
        visible: false,
    },
    toOrder() {
        wx.navigateTo({
            url: "/pages/order-list/order-list"
        })
    },
    onFocus() {
        const allData = []
        this.data.shopList.forEach((item, index) => {
            allData.push(...item.map(v => {
                v.pindex = index
                return v
            }))
        })
        wx.navigateTo({
            url: "/pages/search-order/search-order",
            success: event => {
                const {currentGoodList} = this.data
                event.eventChannel.emit('getCartData', [currentGoodList, allData])
            },
            events: {
                delHandler: ev => {
                    this.deleteCart(ev)
                },
                addHandler: ev => {
                    this.addCart(ev)
                }
            }
        })
    },
    resetCard() {
        const {shopList, store, activeRoom} = this.data
        this.setData({
            // cartData: {...cartData},
            currentGoodList: [],
            totalNum: 0,
            totalPrice: 0,
        })
        wx.setStorageSync(NAME_ENUM, [])
        this.initShopCategory(store.id,)
        // wx.setTabBarBadge({
        //     index: 2,
        //     text: '',
        // })
    },
    toDetail(ev) {
        const {id} = ev.currentTarget.dataset
        wx.navigateTo({
            url: "/pages/good-detail/good-detail?id=" + id
        })
    },
    confirmOrder() {
        const hasMobile = app.checkHasMobile()
        if (!hasMobile) return
        const {store, activeRoom: room, currentGoodList} = this.data
        if (!room.name) return toast({title: '请选择包间'})
        if (currentGoodList.length === 0) return toast({title: '您没有选购商品'})
        wx.navigateTo({
            url: "/pages/order-detail/order-detail",
            events: {
                addSuccess: ({roomID, storeID}) => {
                    this.resetCard(roomID, storeID)
                },
            },
            success: event => {
                event.eventChannel.emit('getOrder', {
                    store,
                    good: currentGoodList,
                    room
                })
            },

        })
    },
    getOrderList(store_id, room_id) {
        app.ajax({
            url: '/api/food/foodgoodslists',
            data: {
                store_id, room_id
            },
            success: resp => {
                console.log(resp, '已点的')
            },
            fail: err => {
                console.log(err, 'error')
            }
        })
    },
    getBanner() {
        app.ajax({
            url: '/api/banner/bannerlist',
            data: {type: 3},
            success: res => {
                this.setData({
                    banner: res.data
                })
            }
        })
    },
    delGood(good, storeID) {
        const {totalNum, totalPrice, currentGoodList} = this.data
        const list = currentGoodList
        const index = list.findIndex(item => item.id === good.id)
        const curNum = list[index].num
        const v = curNum - 1
        list[index].num = v > 0 ? v : 0
        const totalMoney = (Number(totalPrice) - Number(good.price)).toFixed(2)
        this.setData({
            currentGoodList: list.filter(item => item.num > 0),
            totalPrice: totalMoney,
            totalNum: totalNum - 1,
        })
        wx.setStorageSync(NAME_ENUM, currentGoodList)
    },
    calcSpecGoodNumber(number, id) {
        const {currentGoodList} = this.data
        const target = currentGoodList.filter(item => item.id === id)
        console.log(target, '购物车target')
        if (!target || !target.length) return number
        return number + target.reduce((pre, cur) => {
            return pre + cur.specNumber
        }, 0)
    },

    chooseSpecSuccess(ev) {
        const {currentGoodList, shopList} = this.data
        const {index, number, specId, specName, goodsData} = ev.detail
        const {id} = goodsData
        const targetList = shopList[index]
        if (!targetList) return;
        const goodsDataTarget = targetList.find(item => item.id === id)
        const cloneData = cloneDataFunc(goodsDataTarget)
        if (!goodsDataTarget) return;
        if (!goodsDataTarget.haveSpec) return
        goodsDataTarget.num = this.calcSpecGoodNumber(number, id)
        this.setData({shopList: [...shopList]})
        // 查找 当前购物车中是否存在 当前商品选择的当前 spec
        const cartTarget = currentGoodList.find(item => item.id === id && item.haveSpec && item.targetSpec === specId)
        if (!cartTarget) {
            cloneData.targetSpec = specId
            cloneData.targetSpecName = specName
            cloneData.specNumber = number
            cloneData.specTotal = (number * cloneData.price).toFixed(2)
            this.addSpecGood(cloneData, number)
        } else {
            const {totalPrice, totalNum} = this.data
            cartTarget.specNumber += number
            cartTarget.specTotal = (cartTarget.specNumber * cartTarget.price).toFixed(2)
            this.setData({
                currentGoodList,
                totalNum: totalNum + number,
                totalPrice: (Number(totalPrice) + Number(cartTarget.price * number)).toFixed(2)
            })
            wx.setStorageSync(NAME_ENUM, currentGoodList)
        }
    },
    addSpecGood(goodsData, total) {
        const {totalPrice, currentGoodList: list, totalNum} = this.data
        list.push(goodsData)
        const totalMoney = (Number(totalPrice) + Number(goodsData.specTotal)).toFixed(2)
        this.setData({
            currentGoodList: [...list],
            totalPrice: totalMoney,
            totalNum: totalNum + total,
        })
        wx.setStorageSync(NAME_ENUM, list)
        toast({title: '添加成功'})
    },
    deleteCart(ev) {
        const {good, index} = ev.currentTarget.dataset
        const {store, activeRoom: room, shopList} = this.data
        const target = shopList[index]
        const {id} = good
        console.log(index, shopList)
        const targetGood = target.find(item => item.id === id)
        targetGood.num -= 1
        this.setData({
            shopList: [...shopList]
        })
        this.delGood(good, store.id)
    },
    addGood(good) {
        const {totalNum, totalPrice, currentGoodList} = this.data
        let list = currentGoodList
        const index = list.findIndex(item => item.id === good.id)
        if (index !== -1) {
            const curNum = list[index].num
            list[index].num = curNum + 1
        } else {
            good.num = 1
            list.push(good)
        }
        const totalMoney = (Number(totalPrice) + Number(good.price)).toFixed(2)
        this.setData({
            currentGoodList: [...list],
            totalPrice: totalMoney,
            totalNum: totalNum + 1,
        })
        wx.setStorageSync(NAME_ENUM, currentGoodList)
        toast({title: '添加成功'})
    },
    addCart(ev) {
        const {good, index} = ev.currentTarget.dataset
        const {store, activeRoom: room, shopList} = this.data
        const target = shopList[index]
        const {id} = good
        const targetGood = target.find(item => item.id === id)
        targetGood.num += 1
        this.setData({shopList: [...shopList]})
        this.addGood(good, store.id, room.id)
    },
    chooseSpec(ev) {
        const {index, good} = ev.currentTarget.dataset
        const target = this.selectComponent('#specPopup')
        target && target.open(index, good)
    },
    initShopCategory(store_id, cartData = []) {
        let specMap = {}
        if (cartData) specMap = this.calcSpecMap(cartData)
        const targetList = this.data.currentGoodList
        console.log(targetList, 'targetList')
        app.ajax({
            url: '/api/food/foodcategory',
            data: {store_id},
            success: resp => {
                const {code, data, msg} = resp
                if (code !== 1) return toast({title: msg})
                const list = []
                const category = data.map(item => {
                    let {category_id: id, category_name: title, good_items} = item
                    if (!good_items) good_items = []
                    // if (good_items.length) good_items[0].is_kaiqilengre = 1
                    good_items.forEach(item => {
                        const {num, is_kaiqilengre} = item
                        item.count = num
                        item.num = 0
                        const haveSpec = is_kaiqilengre > 0
                        item.haveSpec = haveSpec
                        if (!targetList || !targetList.length) {
                            item.num = 0
                        } else {
                            if (haveSpec && specMap.hasOwnProperty(item.id)) {
                                item.num = specMap[item.id]
                            } else {
                                const hasItem = targetList.find(t => t.id === item.id)
                                if (hasItem) item.num = hasItem.num
                            }
                        }
                    })
                    list.push(good_items)
                    return {id, title}
                })
                app.setShopList(list)
                this.setData({
                    category: [...category],
                    shopList: [...list],
                })
                setTimeout(() => {
                    this.initRect()
                }, 100)
            }
        })
    },
    pickerChange(ev) {
        const {value} = ev.detail
        const target = this.data.roomList[value * 1]
        this.setData({
            activeRoom: {...target}
        })
    },
    choseConfirm(ev) {
        const {value, index} = ev.detail
        const {defaultIndex, store} = this.data
        this.setData({
            defaultIndex: index,
            activeRoom: {...value}
        })
        this.onClose()
    },
    getCateID(index) {
        return `cate_${index}`
    },
    getShopID(index) {
        return `shop_${index}`
    },
    addGoodSuccess(good) {
        const {activeRoom, store} = this.data
        const {id: roomID} = activeRoom
        const {id: storeID} = store
        setTimeout(() => {
            this.addGood(good, storeID, roomID)
        }, 100)
    },
    onUnload() {
        EventBus.$off('addGoodSuccess', this.addGoodSuccess)
        // EventBus.$off('paySuccess', this.paySuccess)
    },
    async getRoomList(storeid) {
        return new Promise(resolve => {
            app.ajax({
                url: "/api/room/selcetroombystore",
                data: {storeid},
                success: res => {
                    const {code, data, msg} = res
                    if (code !== 1) {
                        return resolve([true, null])
                    }
                    resolve([null, data])
                }
            })
        })
    },
    async initRoomList(id, loading) {
        const [error, roomList] = await this.getRoomList(id)
        if (error) {
            if (loading) {
                wx.hideLoading()
            }
            return wx.showModal({
                title: '温馨提示',
                content: '获取包间列表失败,请刷新页面或者重新选择店铺在进行点餐吧!'
            })
        }
        const data = roomList.map(item => {
            const {id, name} = item
            return {id, name}
        })
        this.setData({
            roomList: data
        })
        if (loading) {
            wx.hideLoading()
        }
    },
    onShow() {
        console.log('onShow')
        const store = app.getFirst()
        if (!store) {
            return toast({title: '请先选择店铺'}, () => {
                wx.redirectTo({
                    url: "/pages/store-list/store-list"
                })
            })
        }
        const showLoading = this.data.roomList.length === 0
        if (showLoading) {
            wx.showLoading({
                title: '正在获取数据',
                mask: true,
            })
        }
        const {id} = store
        this.initRoomList(id, showLoading)
        const list = this.readCache(id)
        console.log(list, 'readCache')
        this.initShopCategory(id, list)
        this.setData({store})
    },
    onLoad() {
        this.getBanner()
        EventBus.$on('addGoodSuccess', this.addGoodSuccess)
        // EventBus.$on('paySuccess', this.paySuccess)
        // toast({title: "正在开发中..."})
    },
    onClose() {
        this.setData({show: false})
    },
    showPicker() {
        this.setData({show: true})
    },


    initRect() {
        let selector = wx.createSelectorQuery()
        selector.selectAll('.shop-group-wrapper').boundingClientRect(rect => {
            let array = [0]
            let height = 0
            rect.forEach(item => {
                height += item.height
                array.push(height)
            })
            heightArr.splice(0, heightArr.length, ...array)
        }).exec()
    },
    calcTotalNum() {
        const {currentGoodList} = this.data
        const {num, price} = currentGoodList.reduce((pre, cur) => {
            let {num, price, haveSpec, specNumber} = cur
            const {num: _num, price: _price} = pre
            if (haveSpec) {
                num = specNumber
            }
            return {
                num: num + _num,
                price: _price + (num * price)
            }
        }, {num: 0, price: 0})
        this.setData({
            totalNum: num,
            totalPrice: price,
        })
    },
    calcSpecMap(list) {
        const specMap = {}
        list.forEach(item => {
            const {haveSpec, id, specNumber} = item
            if (!haveSpec) return
            if (!specMap[id]) return specMap[id] = specNumber
            specMap[id] += specNumber
        })
        return specMap
    },
    readCache() {
        const value = wx.getStorageSync(NAME_ENUM)
        let currentList = [];
        if (!!value && value.length) currentList = value
        this.setData({currentGoodList: currentList})
        this.calcTotalNum()
        return currentList
    },
    scrollHandler(ev) {
        const {scrollTop} = ev.detail
        const targetIndex = heightArr.findIndex((item, index) => scrollTop > item && scrollTop < heightArr[index + 1])
        if (targetIndex === -1) return
        this.setData({
            activeCateIndex: targetIndex
        })
    },
    clearAllGood() {
        const {store, cartData, shopList} = this.data
        cartData[store.id] = []
        const value = shopList.map(good => {
            return good.map(item => {
                item.num = 0
                return item
            })
        })
        this.setData({
            currentGoodList: [],
            visible: false,
            shopList: value,
            totalPrice: 0,
            totalNum: 0,
        })
        wx.setStorageSync(NAME_ENUM, [])
    },
    initGoodNums(list) {
        const {shopList} = this.data
        if (!list || !list.length) {
            return this.setData({
                shopList: shopList.map(list => {
                    return list.map(food => {
                        return {...food, num: 0}
                    })
                })
            })
        }
        const specMap = this.calcSpecMap(list)
        // shopList.forEach(goods => {
        //     goods.forEach(item => {
        //         const target = list.find(t => t.id === item.id)
        //         if (!target) return
        //         const {num} = target
        //         item.num = num
        //     })
        // })
        const result = shopList.map(goods => {
            return goods.map(item => {
                if (item.haveSpec) {
                    specMap[item.id] ? item.num = specMap[item.id] : item.num = 0
                    return item
                }
                const target = list.find(t => t.id === item.id)
                if (target) {
                    const {num} = target
                    item.num = num
                }
                return item
            })
        })
        this.setData({
            shopList: result
        })
    },
    changeNumHandlerBySpecGoods(id, specId, type) {
        const {currentGoodList} = this.data
        const target = currentGoodList.find(item => item.id === id && item.targetSpec === specId)
        if (!target) return
        type === "increment" ? target.specNumber += 1 : target.specNumber -= 1
        if (target.specNumber > 0) {
            target.specTotal = (target.specNumber * target.price).toFixed(2)
        }
        const value = currentGoodList.filter(item => {
            if (item.haveSpec) return item.specNumber > 0
            return item.num > 0
        })
        this.setData({
            visible: value.length !== 0,
            currentGoodList: value
        })
        this.initGoodNums(value)
        this.calcTotalNum()
        wx.setStorageSync(NAME_ENUM, value)
    },
    changeNumHandler(ev) {
        const {id, type, spec, specId} = ev.detail
        if (spec) return this.changeNumHandlerBySpecGoods(id, specId, type)
        const {currentGoodList, cartData, store} = this.data
        const index = currentGoodList.findIndex(item => item.id === id)
        if (index === -1) return;
        const target = currentGoodList[index]
        if (!target) return
        const {num} = target
        if (type === 'increment') {
            target.num = num + 1
        } else {
            target.num = num - 1
        }
        const value = currentGoodList.filter(item => item.num > 0)
        this.setData({
            visible: value.length !== 0,
            currentGoodList: value
        })
        this.initGoodNums(value)
        this.calcTotalNum()
        wx.setStorageSync(NAME_ENUM, value)
    },
    clickCategory(ev) {
        const {index} = ev.currentTarget.dataset
        const {activeCateIndex} = this.data
        const id = this.getShopID(index)
        if (index !== activeCateIndex) {
            this.setData({
                activeCateIndex: index,
                rightID: id,
            })
        }
    },
    closePopup() {
        this.setData({
            visible: false
        })
    },
    showCart() {
        const {currentGoodList} = this.data
        if (currentGoodList.length === 0) return toast({title: '没有添加任何商品'})
        this.setData({
            visible: true
        })
    }

});
